package com.zhang.user.thrift;


import com.zhang.thrift.message.MessageService;
import com.zhang.thrift.user.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.thrift.TServiceClient;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**Thrift客户端，去操作服务类，需要知道服务端的IP和端口号--客户端需要和服务端的参数设置成一样
 * Created by Michael on 2017/10/30.
 */
@Component
@Slf4j
public class ServiceProvider {

    //配置文件
    @Value("${thrift.user.ip}")
    private String serverIp;

    @Value("${thrift.user.port}")
    private int serverPort;

    @Value("${thrift.message.ip}")
    private String messageServerIp;
    @Value("${thrift.message.port}")
    private int messageServerPort;

    /**
     * 枚举
     */
    private enum ServiceType {
        USER,
        MESSAGE
    }

    /**
     * 获取用户服务：用于登录注册
     * @return
     */
    public UserService.Client getUserService() {

        return getService(serverIp, serverPort, ServiceType.USER);
    }

    /**
     * 获取信息服务：用于发送短信或者邮件
     * @return
     */
    public MessageService.Client getMessasgeService() {

        return getService(messageServerIp, messageServerPort, ServiceType.MESSAGE);
    }

    public <T> T getService(String ip, int port, ServiceType serviceType) { //连接服务端，构建客户端
        TSocket socket = new TSocket(ip, port, 3000);  //与服务端保持一致
        log.info("getService:ServiceType:{},ip:{},port:{}",serviceType,ip, port);
        TTransport transport = new TFramedTransport(socket);
        try {
            transport.open();
            log.info("transport.open();");
        } catch (TTransportException e) {
            e.printStackTrace();
            return null;
        }
        TProtocol protocol = new TBinaryProtocol(transport);

        TServiceClient result = null;
        switch (serviceType) {
            case USER:
                result = new UserService.Client(protocol);   //用户服务客户端（自动生成的？）---用于和用户服务通信？
                break;
            case MESSAGE:
                result = new MessageService.Client(protocol);
                break;
        }
        return (T)result;
    }

}
